package com.lechuang.ssgou.view.activity.soufanli;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.lechuang.ssgou.R;
import com.lechuang.ssgou.base.BaseFragment;
import com.lechuang.ssgou.base.Constants;
import com.lechuang.ssgou.model.bean.CountBean;
import com.lechuang.ssgou.model.bean.HomeKindBean;
import com.lechuang.ssgou.model.bean.SoufanliProgremBean;
import com.lechuang.ssgou.model.bean.SoufanliResultBean;
import com.lechuang.ssgou.presenter.CommonAdapter;
import com.lechuang.ssgou.presenter.adapter.SoufanliRecyclerAdapter;
import com.lechuang.ssgou.presenter.net.Netword;
import com.lechuang.ssgou.presenter.net.ResultBack;
import com.lechuang.ssgou.presenter.net.netApi.HomeApi;
import com.lechuang.ssgou.utils.Utils;
import com.lechuang.ssgou.view.activity.home.KindDetailActivity;
import com.lechuang.ssgou.view.activity.home.ProductDetailsActivity;
import com.lechuang.ssgou.view.activity.home.ProgramDetailActivity;
import com.lechuang.ssgou.view.activity.home.SearchResultActivity;
import com.lechuang.ssgou.view.defineView.MGridView;
import com.lechuang.ssgou.view.defineView.ViewHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 作者：li on 2017/9/21 17:46
 * 邮箱：961567115@qq.com
 * 修改备注:
 */
public class SouFanLiFragment extends BaseFragment {

    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.iv_program1)
    ImageView ivProgram1;
    @BindView(R.id.iv_program2)
    ImageView ivProgram2;
    @BindView(R.id.iv_program3)
    ImageView ivProgram3;
    @BindView(R.id.iv_program4)
    ImageView ivProgram4;
    @BindView(R.id.gv_kind)
    MGridView gvKind;
    @BindView(R.id.rv_soufanli)
    RecyclerView rvSoufanli;
    Unbinder unbinder;
    @BindView(R.id.refreshScrollView)
    PullToRefreshScrollView refreshScrollView;
    @BindView(R.id.countNumber)
    TextView countNumber;
    @BindView(R.id.search)
    ImageView search;
    @BindView(R.id.ll_program)
    LinearLayout llProgram;
    @BindView(R.id.searchInfo)
    TextView searchInfo;
    @BindView(R.id.ll_guss)
    LinearLayout llGuss;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_suofanli, container, false);
        unbinder = ButterKnife.bind(this, inflate);
        sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
        //刷新监听
        refreshScrollView.setOnRefreshListener(refresh);
        initData();
        return inflate;
    }

    private void initData() {
        showWaitDialog("");
        initCont();
        initKin();
        initProgrem();
        initRecycle();
    }

    @Override
    public void onStart() {
        super.onStart();
        if (sp.getBoolean("isLogin", false)) {
            llGuss.setVisibility(View.VISIBLE);
        } else {
            llGuss.setVisibility(View.GONE);
        }
    }

    private void initCont() {
        Netword.getInstance().getApi(HomeApi.class)
                .countSum()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ResultBack<CountBean>(getActivity()) {
                    @Override
                    public void successed(CountBean result) {
                        countNumber.setText(result.couponCount);
                    }
                });
    }

    private void initProgrem() {
        Netword.getInstance().getApi(HomeApi.class)
                .soufanliProgramaImg()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ResultBack<SoufanliProgremBean>(getActivity()) {
                    @Override
                    public void successed(SoufanliProgremBean result) {
                        if (result == null) {
                            return;
                        }
                        final List<SoufanliProgremBean.SearchImgListBean> list = result.searchImgList;
                        List<String> imgList = new ArrayList<>();
                        for (int i = 0; i < list.size(); i++) {
                            if (list.get(i) != null)
                                imgList.add(list.get(i).img);
                        }
                        //栏目1
                        if (imgList.get(0) != null)
                            Glide.with(getActivity()).load(imgList.get(0)).into(ivProgram1);
                        //栏目2
                        if (imgList.get(1) != null)
                            Glide.with(getActivity()).load(imgList.get(1)).into(ivProgram2);
                        //栏目3
                        if (imgList.get(2) != null)
                            Glide.with(getActivity()).load(imgList.get(2)).into(ivProgram3);
                        //栏目4
                        if (imgList.get(3) != null)
                            Glide.with(getActivity()).load(imgList.get(3)).into(ivProgram4);
                        ivProgram1.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                startActivity(new Intent(getActivity(), KindDetailActivity.class)
                                        .putExtra("type", list.get(0).programType));
                            }
                        });
                        ivProgram2.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                startActivity(new Intent(getActivity(), KindDetailActivity.class)
                                        .putExtra("type", list.get(1).programType));
                            }
                        });
                        ivProgram3.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                startActivity(new Intent(getActivity(), KindDetailActivity.class)
                                        .putExtra("type", list.get(2).programType));
                            }
                        });
                        ivProgram4.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                startActivity(new Intent(getActivity(), KindDetailActivity.class)
                                        .putExtra("type", list.get(3).programType));
                            }
                        });
                    }
                });
    }

    private void initKin() {
        Netword.getInstance().getApi(HomeApi.class)
                .homeClassify()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ResultBack<HomeKindBean>(getActivity()) {
                    @Override
                    public void successed(HomeKindBean result) {
                        if (result == null) {
                            return;
                        }
                        List<HomeKindBean.ListBean> list = result.tbclassTypeList;
                        //取前10类
                        if (list.size() > 10) {
                            list = list.subList(0, 10);
                        }
                        gvKind.setAdapter(new CommonAdapter<HomeKindBean.ListBean>(getActivity(), list, R.layout.home_kinds_item) {
                            @Override
                            public void setData(ViewHolder viewHolder, Object item) {
                                HomeKindBean.ListBean bean = (HomeKindBean.ListBean) item;
                                //分类名称
                                viewHolder.setText(R.id.tv_kinds_name, bean.rootName);
                                //分类图片
                                viewHolder.displayImage(R.id.iv_kinds_img, bean.img);
                            }
                        });
                        final List<HomeKindBean.ListBean> list1 = result.tbclassTypeList;
                        // TODO: 2017/10/2  分类item
                        gvKind.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                Intent intent = new Intent(getActivity(), SearchResultActivity.class);
                                //传递一个值,搜索结果页面用来判断是从分类还是搜索跳过去的 1:分类 2:搜索界面
                                intent.putExtra("type", 1);
                                //rootName传递过去显示在搜索框上
                                intent.putExtra("rootName", list1.get(position).rootName);
                                //rootId传递过去入参
                                intent.putExtra("rootId", list1.get(position).rootId + "");
                                startActivity(intent);
                            }
                        });
                    }
                });
    }

    HashMap<String, String> map = new HashMap<>();
    int page = 1;
    int rootId = -1;
    SharedPreferences sp;
    //底部数据展示
    private SoufanliRecyclerAdapter mAdapter;
    private List<SoufanliResultBean.ProductListBean> productList = new ArrayList<>();

    private void initRecycle() {
        Netword.getInstance().getApi(HomeApi.class)
                .soufanliProduct(page)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ResultBack<SoufanliResultBean>(getActivity()) {
                    @Override
                    public void successed(SoufanliResultBean result) {

                        hideWaitDialog();
                        if (result == null || result.productList == null) {
                            Utils.show(getActivity(), "亲,已经到底了~");
                            return;
                        }
                        List<SoufanliResultBean.ProductListBean> list = result.productList;
                        refreshScrollView.setMode(list.size() > 0 ? PullToRefreshBase.Mode.BOTH : PullToRefreshBase.Mode.PULL_FROM_START);
                        if (page == 1) {
                            productList.clear();
                        }
                        productList.addAll(list);
                        if (page > 1 && list.isEmpty()) {
                            Utils.show(getActivity(), "亲,已经到底了~");
                            return;
                        }
                        int isAgencyStatus = sp.getInt("isAgencyStatus", 0);

                        if (mAdapter == null) {
                            mAdapter = new SoufanliRecyclerAdapter(productList, getContext(), isAgencyStatus);
                            rvSoufanli.setLayoutManager(new LinearLayoutManager(getContext()));
                            rvSoufanli.setAdapter(mAdapter);
                            mAdapter.setOnItemClickLitener(new SoufanliRecyclerAdapter.OnItemClickLitener() {
                                @Override
                                public void onItemClick(View view, int position) {
                                    startActivity(new Intent(getActivity(), ProductDetailsActivity.class)
                                            //.putExtra("alipayCouponId", productList.get(position).alipayCouponId)
                                            .putExtra(Constants.listInfo, JSON.toJSONString(productList.get(position))));
                                }
                            });
                            rvSoufanli.setNestedScrollingEnabled(false);
                        } else {
                            mAdapter.notifyDataSetChanged();
                        }


                    }
                });
    }

    //刷新加载
    private PullToRefreshBase.OnRefreshListener2 refresh = new PullToRefreshBase.OnRefreshListener2() {

        @Override
        public void onPullDownToRefresh(PullToRefreshBase refreshView) {

            // 显示最后更新的时间
            //refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
            page = 1;
            initData();
            refreshScrollView.onRefreshComplete();
        }

        @Override
        public void onPullUpToRefresh(PullToRefreshBase refreshView) {
            // 显示最后更新的时间
            //refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
            showWaitDialog("");
            page += 1;
            initRecycle();
            refreshScrollView.onRefreshComplete();
        }
    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    @OnClick({R.id.searchInfo, R.id.search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.searchInfo:
                startActivity(new Intent(getActivity(), SoufanliInfo.class));
                break;
            case R.id.search:
                //搜索内容
                String search = etContent.getText().toString().trim();
                if (search == null || search.isEmpty()) {
                    Utils.show(getActivity(), "搜索内容不能为空");
                    return;
                }
                //判断是否包含Emoji表情
                if (Utils.containsEmoji(search)) {
                    Utils.show(getActivity(), getActivity().getResources().getString(R.string.no_emoji));
                    return;
                }

                Intent intent = new Intent(getActivity(), SearchResultActivity.class);
                intent.putExtra("type", 2);
                //rootName传递过去显示在搜索框上
                intent.putExtra("rootName", search);
                //rootId传递过去入参
                intent.putExtra("rootId", search);
                startActivity(intent);
                break;
        }
    }
}